﻿$(document).ready(function () {
  $("#register-link").colorbox({
    inline: true,
    href: "#register-form",
    title: "Регистрация",
    callback: loadFields
  });
  $("#user_new").ready(loadFields)
});

function loadFields() {
  if ($("#user-faculty").length == 0) {
    getFacultiesList(parseFacultiesAsOptionsList);
    $("#profile-fields").removeClass("hide");
  }
}

function parseFacultiesAsOptionsList(faculties)
{
  select = $("#user_profile_attributes_faculty").empty().append("<option value=0>Select faculty</option>")
  $(faculties).each(function() {
    option = "<option value='" + this.id + "'>" + this.name + "</option>"
    select.append(option);
  });
  
  select.change(function () {
    if (this.value > 0) {
      getFacultyWithGroups(this.value, parseSingleFacultyGroupsAsOptionsList)
    } else {
      $("#groups-list").addClass("hide")
      $.colorbox.resize()
    }
  })
}

function parseSingleFacultyGroupsAsOptionsList (faculty) {
  select = $("#user_profile_attributes_group")
  select.empty()
  $(faculty.groups).each(function () {
    option = "<option value='" + this.id + "'>" + this.title + "</option>"
    select.append(option);
  })
  
  $("#groups-list").removeClass("hide")
  $.colorbox.resize()
}